package cool.mtc.web.util;

import cool.mtc.core.exception.ServiceException;
import cool.mtc.core.util.StringUtil;
import org.springframework.http.MediaType;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;

/**
 * @author 明河
 */
public abstract class HttpUtil {

    public static void setImageResponse(HttpServletResponse response) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0L);
        response.setContentType("image/jpeg");
    }

    public static void writeToResponse(HttpServletResponse response, BufferedImage image) {
        try {
            OutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "jpeg", outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException var3) {
            throw new ServiceException("无法将该图片写入指定位置");
        }
    }

    public static void writeToResponse(HttpServletResponse response, String str) throws IOException {
        setJsonResponse(response);
        response.getWriter().print(str);
    }

    public static void setJsonResponse(HttpServletResponse response) {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
    }

    /**
     * 获取IP
     */
    public static String getIP(HttpServletRequest request) {
        String unKnownStr = "unKnown";
        String xIp = request.getHeader("X-Real-IP");
        String xFor = request.getHeader("X-Forwarded-For");
        if (StringUtil.isNotEmpty(xFor) && !unKnownStr.equalsIgnoreCase(xFor)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = xFor.indexOf(",");
            if (index != -1) {
                return xFor.substring(0, index);
            } else {
                return xFor;
            }
        }
        xFor = xIp;
        if (StringUtil.isNotEmpty(xFor) && !unKnownStr.equalsIgnoreCase(xFor)) {
            return xFor;
        }
        if (StringUtil.isEmpty(xFor) || unKnownStr.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtil.isEmpty(xFor) || unKnownStr.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtil.isEmpty(xFor) || unKnownStr.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtil.isEmpty(xFor) || unKnownStr.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtil.isEmpty(xFor) || unKnownStr.equalsIgnoreCase(xFor)) {
            xFor = request.getRemoteAddr();
        }
        return xFor;
    }

    /**
     * 获取 User-Agent
     */
    public static String getUserAgent(HttpServletRequest request) {
        return request.getHeader("User-Agent");
    }

    public static <T> String beanToGetRequestParam(T t) {
        Field[] fields = t.getClass().getDeclaredFields();
        if (fields.length == 0) {
            return StringUtil.EMPTY;
        }
        StringBuilder param = new StringBuilder();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            if (i > 0) {
                param.append("&");
            }
            param.append(field.getName()).append("=");
            try {
                Object value = field.get(t);
                if (null != value) {
                    param.append(value);
                }
            } catch (IllegalAccessException ignore) {
            }
        }
        return param.toString();
    }
}
